package cn.liujianbo.example.base.classloader;

import java.io.File;
import java.net.URLClassLoader;
import java.util.Map;

/**
 * @author 刘建波
 * @date 2021-12-02 21:35
 */
public class WatchDog implements Runnable {
    private Map<String, Long> fileSnapshot;
    private URLClassLoader classLoader;

    public WatchDog(URLClassLoader classLoader, Map<String, Long> map) {
        this.fileSnapshot = map;
        this.classLoader = classLoader;
    }
    @Override
    public void run() {
        File file = new File(this.getClass().getResource("").getPath());
        File[] files = file.listFiles();
        for (File f : files) {
            long lastModified = f.lastModified();
            Long preModified = fileSnapshot.get(f.getPath());
            if (lastModified != preModified) {
                System.out.println(f.getName());
                // 文件最后修改时间不一致，需要重新加载类
                loadClas(f.getName());
            }
        }
    }

    private void loadClas(String name) {
        try {
            System.out.println(Thread.currentThread().getName() + "重新加载MyLog类");
            classLoader.loadClass(name.replace(".class", ""));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
